Page({
  data: {
    submitting: false,
    form: {
      name: '',
      wechat: '',
      phone: wx.getStorageSync('phone') || '',
      positionCode: '',
      positionName: '',
      orgName: '',
      hiringNumber: '',
      rank: '',
      idPhoto: '',
      scoreShot: '',
      scopeLabel: '',
      referrer: ''
    },
    classTypes: ['面试班', '冲刺班', '精品班', 'VIP班'],
    classTypeIndex: -1,
    agreements: ['协议班', '非协议班'],
    agreementIndex: -1,
    discounts: ['无', '老学员', '老学员推荐'],
    discountIndex: 0
  },

  onLoad(options) {
    if (options && options.positionCode) {
      this.setData({ 'form.positionCode': options.positionCode })
    }
    if (options && options.courseId) this.courseId = options.courseId
  },

  onInput(e) {
    const field = e.currentTarget.dataset.field
    this.setData({ [`form.${field}`]: e.detail.value })
  },

  onClassTypeChange(e) {
    this.setData({ classTypeIndex: Number(e.detail.value) })
  },
  onAgreementChange(e) {
    this.setData({ agreementIndex: Number(e.detail.value) })
  },
  onDiscountChange(e) {
    this.setData({ discountIndex: Number(e.detail.value) })
  },

  chooseIdPhoto() {
    this.chooseOneImage((path) => this.setData({ 'form.idPhoto': path }))
  },
  chooseScoreShot() {
    this.chooseOneImage((path) => this.setData({ 'form.scoreShot': path }))
  },
  chooseOneImage(cb) {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      success: (res) => {
        const file = res.tempFiles[0]
        const path = file.tempFilePath
        const size = file.size // 单位：Byte
  
        // 1️⃣ 限制大小：最大 5MB
        const maxSize = 5 * 1024 * 1024
        if (size > maxSize) {
          wx.showToast({ title: '图片大小不能超过 5MB', icon: 'none' })
          return
        }
  
        // 2️⃣ 限制格式：只允许 jpg / jpeg / png
        const validExt = ['jpg', 'jpeg', 'png']
        const ext = path.split('.').pop().toLowerCase()
        if (!validExt.includes(ext)) {
          wx.showToast({ title: '仅支持 JPG、JPEG、PNG 格式', icon: 'none' })
          return
        }
  
        cb && cb(path)
      },
      fail: () => {
        wx.showToast({ title: '选择图片失败', icon: 'none' })
      }
    })
  },

  onPositionCodeBlur() {
    const code = this.data.form.positionCode.trim()
    if (!code) return
    // 这里调用实际接口获取岗位信息
    wx.request({
      url: 'https://your-api.com/position/detail',
      method: 'GET',
      data: { code },
      success: (res) => {
        if (res.statusCode === 200 && res.data) {
          this.setData({
            'form.positionName': res.data.positionName || '',
            'form.orgName': res.data.orgName || '',
            'form.hiringNumber': String(res.data.hiringNumber || '')
          })
        }
      }
    })
  },

  onRankBlur() {
    const rank = Number(this.data.form.rank)
    const hiring = Number(this.data.form.hiringNumber)
    if (!rank || !hiring) return
    let scope = ''
    if (hiring <= 3) {
      if (rank <= hiring) scope = '小围'
      else if (rank <= 2 * hiring) scope = '中围'
      else if (rank <= 5 * hiring) scope = '大围'
    } else if (hiring === 4) {
      if (rank <= 3) scope = '小围'
      else if (rank <= 6) scope = '中围'
      else if (rank <= 14) scope = '大围'
    } else if (hiring === 5) {
      if (rank <= 4) scope = '小围'
      else if (rank <= 8) scope = '中围'
      else if (rank <= 18) scope = '大围'
    }
    this.setData({ 'form.scopeLabel': scope })
  },

  // 取消报名：退出小程序
  onCancel() {
    if (wx.exitMiniProgram) {
      wx.exitMiniProgram({})
    } else {
      wx.showToast({ title: '当前环境不支持退出', icon: 'none' })
      wx.reLaunch({ url: '/pages/index/index' })
    }
  },

  // 提交报名：调用接口后根据状态跳转
  onSubmit() {
    if (this.data.submitting) return
    // 简单校验
    const f = this.data.form
    if (!f.name || !f.wechat || !f.phone || !f.positionCode || !f.rank) {
      wx.showToast({ title: '请先完善必填项', icon: 'none' })
      return
    }
    if (this.data.classTypeIndex < 0 || this.data.agreementIndex < 0) {
      wx.showToast({ title: '请选择班型与协议类型', icon: 'none' })
      return
    }
    this.setData({ submitting: true })

    const api = 'https://your-api.com/app/submit'
    const payload = { ...this.data.form, courseId: this.courseId || '',
      classType: this.data.classTypes[this.data.classTypeIndex] || '',
      agreement: this.data.agreements[this.data.agreementIndex] || '',
      discount: this.data.discounts[this.data.discountIndex] || ''
    }

    wx.request({
      url: api,
      method: 'POST',
      data: payload,
      timeout: 8000,
      success: (res) => {
        let status = 'filled_no_payment'
        if (res.statusCode === 200 && res.data && res.data.status) {
          status = res.data.status
        } else {
          // 本地模拟：可按笔试排名简单分流
          const r = Number(this.data.form.rank) || 0
          if (r > 0 && r <= 3) status = 'approved'
          else if (r <= 6) status = 'submitted_waiting_review'
          else status = 'filled_no_payment'
        }
        this.routeByStatus(status)
      },
      fail: () => {
        // 网络失败也进行本地模拟
        this.routeByStatus('filled_no_payment')
      },
      complete: () => this.setData({ submitting: false })
    })
  },

  // 根据状态路由
  routeByStatus(status) {
    switch (status) {
      case 'filled_no_payment':
        wx.navigateTo({ url: '/pages/result/apply-success/index' })
        break
      case 'submitted_waiting_review':
        wx.navigateTo({ url: '/pages/result/submit-success/index' })
        break
      case 'approved':
        wx.navigateTo({ url: '/pages/result/review-approved/index' })
        break
      default:
        wx.navigateTo({ url: '/pages/result/apply-success/index' })
    }
  }
})
